package com.matrix.rabbitmqtest.publishandconfirm;

import com.matrix.rabbitmqtest.util.AppKeys;
import com.matrix.rabbitmqtest.util.RabbitMQUtil;
import com.matrix.rabbitmqtest.util.RunningTimer;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.MessageProperties;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.stream.IntStream;

/**
 * 单个发布确认
 */
public class SingleConfirmProducer {

    public static final int MSG_COUNT = 1000;

    public static void main(String[] args) throws IOException {
        // 获取一个信道
        Channel channel = RabbitMQUtil.getChannel();
        // 开启发布确认
        channel.confirmSelect();
        // 声明队列
        channel.queueDeclare(AppKeys.QUEUE_NAME,true,false,false,null);
        // 发送100条消息
        RunningTimer timer = new RunningTimer();
        IntStream.range(0,MSG_COUNT).forEach(i->{
            try {
                channel.basicPublish("", AppKeys.QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN,("Hello RabbitMQ"+i).getBytes(StandardCharsets.UTF_8));
                boolean publishOk = channel.waitForConfirms();
                if(publishOk){
                    System.out.println("发布成功");
                }
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println("发布"+MSG_COUNT+"条消息, 耗时:"+timer.end()+"ms");
    }
}
